﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;

namespace HS.EIP.WatchService
{
    public class ExecHelper
    {
        /// <summary>
        /// 执行批处理文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static ExecResult ExecBat(string filePath, bool needToOutputInfo, int waitForExit)
        {
            ExecResult r = new ExecResult();
            r.Success = true;

            //try
            {
                using (Process pro = new Process())
                {
                    FileInfo file = new FileInfo(filePath);
                    pro.StartInfo.WorkingDirectory = file.Directory.FullName;
                    pro.StartInfo.FileName = filePath;
                    pro.StartInfo.CreateNoWindow = true;
                    //pro.StartInfo.RedirectStandardOutput = needToOutputInfo;
                    //pro.StartInfo.RedirectStandardError = needToOutputInfo;
                    //pro.StartInfo.RedirectStandardInput = true;
                    pro.StartInfo.UseShellExecute = false;
                    pro.StartInfo.Verb = "RunAs";
                    pro.Start();
                    //pro.StandardInput.AutoFlush = true;

                    //pro.StandardInput.WriteLine("exit");

                    //pro.StandardInput.Close();

                    //if (needToOutputInfo)
                    //{
                    //    r.OutPutString = pro.StandardOutput.ReadToEnd();
                    //    r.ErrorString = pro.StandardError.ReadToEnd();
                    //}
  
                    pro.WaitForExit(waitForExit*1000);
                }
            }
            //catch (Exception ex)
            //{
            //    r.Success = false;
            //    r.ErrMsg = ex;
            //}
            return r;
        }

        public static ExecResult ExecExe(string filePath, bool needToOutputInfo)
        {
            ExecResult r = new ExecResult();
            r.Success = true;

            //try
            {
                using (Process pro = new Process())
                {
                    FileInfo file = new FileInfo(filePath);
                    pro.StartInfo.WorkingDirectory = file.Directory.FullName;
                    pro.StartInfo.FileName = filePath;
                    pro.StartInfo.CreateNoWindow = true;
                    pro.StartInfo.RedirectStandardOutput = needToOutputInfo;
                    pro.StartInfo.RedirectStandardError = needToOutputInfo;
                    pro.StartInfo.UseShellExecute = false;

                    pro.Start();

                    if (needToOutputInfo)
                    {
                        r.OutPutString = pro.StandardOutput.ReadToEnd();
                        r.ErrorString = pro.StandardError.ReadToEnd();
                    }

                    pro.WaitForExit();
                }
            }
            //catch (Exception ex)
            //{
            //    r.Success = false;
            //    r.ErrMsg = ex;
            //}
            return r;
        }

        public static ExecResult ExecPowerShell(string filePath, bool needToOutputInfo)
        {
            ExecResult r = new ExecResult();
            r.Success = true;

            try
            {
                string scriptText = File.ReadAllText(filePath);
                string outputString = RunScript(scriptText);
                if (needToOutputInfo)
                {
                    r.OutPutString = outputString;
                }
            }
            catch (Exception ex)
            {
                r.Success = false;
                r.ErrMsg = ex;
            }
            return r;
        }

        private static string RunScript(string scriptText)
        {
            Collection<PSObject> results = null;
            // create Powershell runspace  
            using (Runspace runspace = RunspaceFactory.CreateRunspace())
            {
                // open it  
                runspace.Open();
                // create a pipeline and feed it the script text  
                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(scriptText);
                pipeline.Commands.Add("Out-String");

                // execute the script  
                results = pipeline.Invoke();
                // close the runspace  
                runspace.Close();
            }

            // convert the script result into a single string  
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            return stringBuilder.ToString();
        }

        public static void RunScript(List<string> scripts)
        {
            try
            {
                Runspace runspace = RunspaceFactory.CreateRunspace();
                runspace.Open();
                Pipeline pipeline = runspace.CreatePipeline();
                foreach (var scr in scripts)
                {
                    pipeline.Commands.AddScript(scr);
                }
                //返回结果     
                var results = pipeline.Invoke();
                runspace.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(DateTime.Now.ToString() + "日志记录:执行ps命令异常：" + e.Message);
            }
        }
    }
    public class ExecResult
    {
        public bool Success { get; set; }
        /// <summary>
        /// 正常输出
        /// </summary>
        public string OutPutString { get; set; }
        /// <summary>
        /// Erro输出
        /// </summary>
        public string ErrorString { get; set; }
        /// <summary>
        /// 异常信息
        /// </summary>
        public Exception ErrMsg { get; set; }
    }
}
